package server;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

public class Server {
    private ServerSocket serverSocket;

    public Server() {
        try {
            serverSocket = new ServerSocket(8090);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start() {
        try {
            System.out.println("等待客户端连接>>>");
            Socket socket = serverSocket.accept();
            System.out.println("客户端连接成功");
            MyThread mt = new MyThread(socket);
            Thread t = new Thread(mt);
            t.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) {
        Server server = new Server();
        server.start();
    }

    private class MyThread implements Runnable {
        private String host;
        private Socket socket;

        public MyThread(Socket socket) {
            this.socket = socket;
            host = socket.getInetAddress().getHostAddress();
        }

        @Override
        public void run() {
            try {
                InputStream in = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(in, "UTF-8");
                BufferedReader br = new BufferedReader(isr);
                String line;
                while (!"exit".equals(line = br.readLine())) {
                    System.out.println(host+"说:"+line);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}
